﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO.Ports;
using System.Linq;
using System.Speech.Synthesis;
using System.Text;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using GSM900A.Views;

namespace GSM900A.Models
{
    public partial class MainViewModel:ObservableObject
    {

        public ObservableCollection<string> PortNames {  get; set; } 
        public string SelectedPort { get; set; }

        SerialPort serialPort;
        public Logger Logger { get; set; }
        private SpeechSynthesizer synthesizer;
        public MainViewModel()
        {
            Logger = new Logger();
            PortNames=new ObservableCollection<string>();
            GetComCount();

            serialPort = new SerialPort();
            serialPort.DataReceived += SerialPort_DataReceived;

            synthesizer = new SpeechSynthesizer();
            synthesizer.SetOutputToDefaultAudioDevice();
        }
        [ObservableProperty]
        public string message = "This is a test message";
        [ObservableProperty]
        public string phoneNumber;


        //获取串口数量
        #region
        private void GetComCount()
        {
            string[] portNames = SerialPort.GetPortNames();
            foreach (string portName in portNames)
            {
                PortNames.Add(portName);
            }
            if (PortNames.Count > 0)
            {
                SelectedPort = PortNames[0];
            }
        }
        #endregion
        //打开串口
        #region
        [RelayCommand]
        private void Open()
        {
            string selectedPort = SelectedPort;
            if (string.IsNullOrEmpty(selectedPort))
            {
                Logger.WriteLog("请选择有效串口");
                return;
            }
            try
            {
                serialPort = new SerialPort(selectedPort, 9600, Parity.None, 8, StopBits.One);
                serialPort.Open();
                Logger.WriteLog($"串口{selectedPort}已打开");
            }
            catch (Exception ex)
            {
                Logger.WriteLog(ex.ToString());
            }
        }
        #endregion
        //关闭串口
        #region
        [RelayCommand]
        private void Close()
        {
            serialPort.Close();
            Logger.WriteLog($"串口{SelectedPort}已关闭");
        }
        #endregion
        //发送短信
        #region
        [RelayCommand]
        private void SendMsg() 
        {
            if (serialPort == null || !serialPort.IsOpen) 
            {
                Logger.WriteLog("串口未开启");
                return;
            }
            if (string.IsNullOrEmpty(PhoneNumber))
            {
                Logger.WriteLog("电话号码为空");
                return;
            }
            //string phoneNumber = "15619169078";
            //string message = "This is a test message!";

            try
            {
                serialPort.WriteLine("AT+CMGF=1");
                Thread.Sleep(500);

                serialPort.WriteLine($"AT+CMGS={PhoneNumber}");
                Thread.Sleep(500);

                serialPort.WriteLine(Message);
                Thread.Sleep(500);

                //发送ctrl+Z结束短信
                serialPort.Write(new byte[] { 26 }, 0, 1);
                Logger.WriteLog($"短信已发送至[{PhoneNumber}],短信内容为[{Message}]");
            }
            catch (Exception ex) 
            {
                Logger.WriteLog($"发送短信失败：{ex.Message}");
            }
        }
#endregion
        //拨打电话
        #region
        [RelayCommand]
        private void MakeCall() 
        {
            if (serialPort == null || !serialPort.IsOpen)
            {
                Logger.WriteLog("串口未开启");
                return;
            }
            if (string.IsNullOrEmpty(PhoneNumber))
            {
                Logger.WriteLog("电话号码为空");
                return;
            }
            //string phoneNumber = "15619169078";

            try
            {
                serialPort.WriteLine($"ATD{PhoneNumber}");
                Logger.WriteLog($"电话已拨打至{PhoneNumber}");
            }
            catch (Exception ex) 
            {
                Logger.WriteLog($"拨打电话失败{ex.Message}");
            }

        }        
        #endregion
        //挂断电话
        #region
        [RelayCommand]
        private void HangUpCall()
        {
            if (serialPort == null || !serialPort.IsOpen)
            {
                Logger.WriteLog("串口未开启");
                return;
            }
            if (string.IsNullOrEmpty(PhoneNumber))
            {
                Logger.WriteLog("电话号码为空");
                return;
            }

            try
            {
                serialPort.WriteLine("ATH");
                Logger.WriteLog("挂断电话成功");
            }
            catch (Exception ex) 
            {
                Logger.WriteLog($"挂断电话失败{ex.Message}");
            }

        }        
        #endregion
        //朗读发送短信
        #region
        [RelayCommand]
        private void ReadSmsAloud()
        {
            if (string.IsNullOrEmpty(Message)) 
            {
                Logger.WriteLog("短信内容为空");
                return;
            }
            try
            {
                synthesizer.SpeakAsync(Message);
                Logger.WriteLog($"正在朗读短信内容[{Message}]");
            }
            catch (Exception ex) 
            {
                Logger.WriteLog($"朗读短信失败{ex.Message}");
            }
        }
        #endregion
         //朗读接收短信
        #region
        [RelayCommand]
        private void ReadRmsAloud(string message)
        {
            if (string.IsNullOrEmpty(message)) 
            {
                Logger.WriteLog("短信内容为空");
                return;
            }
            try
            {
                synthesizer.SpeakAsync(message);
                Logger.WriteLog($"正在朗读短信内容[{message}]");
            }
            catch (Exception ex) 
            {
                Logger.WriteLog($"朗读短信失败{ex.Message}");
            }
        }
        #endregion
        //接收响应
        #region
        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                string respone = serialPort.ReadExisting();
                Logger.WriteLog($"收到响应：{respone}");

                if (respone.Contains("+CMT:"))
                {
                    string message = ExtractMessageContent(respone);
                    Logger.WriteLog($"收到短信：[{message}]");
                    ReadRmsAloud(message);
                }
            }
            catch (Exception ex)
            {
                Logger.WriteLog($"读取响应失败{ex.Message}");
            }
        }
        private string ExtractMessageContent(string response)
        {
            string[] lines = response.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
            return lines.LastOrDefault();
        }
        #endregion
    }
}
